package com.lyn.seckill.controller;

import com.lyn.seckill.common.ResponseReturnType;
import com.lyn.seckill.common.error.BusinessException;
import com.lyn.seckill.common.error.EnumBusinessError;
import com.lyn.seckill.service.OrderService;
import com.lyn.seckill.service.model.OrderModel;
import com.lyn.seckill.service.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@CrossOrigin(allowCredentials = "true",allowedHeaders = "*")
public class OrderController extends BaseController{

    private final OrderService orderService;
    private final HttpServletRequest httpServletRequest;
    @Autowired
    public OrderController(OrderService orderService, HttpServletRequest httpServletRequest) {
        this.orderService = orderService;
        this.httpServletRequest = httpServletRequest;
    }


    @PostMapping(value = "/orders",consumes = {CONTENT_TYPE_FORMED})
    @ResponseBody
    public ResponseReturnType createOrder(@RequestParam("itemId")Integer itemId,
                                          @RequestParam("amount")Integer amount,
                                          @RequestParam(value = "promoId",required = false)Integer promoId) throws BusinessException {
        Boolean isLogin = (Boolean)httpServletRequest.getSession().getAttribute(EnumBusinessError.IS_LOGIN);
        if (isLogin == null || !isLogin.booleanValue()) {
            throw new BusinessException(EnumBusinessError.USER_NOT_LOGIN);
        }
        UserModel loginUser = (UserModel) httpServletRequest.getSession().getAttribute(EnumBusinessError.LOGIN_USER);
        if (loginUser == null) {
            throw new BusinessException(EnumBusinessError.USER_NOT_LOGIN);
        }
        OrderModel order = orderService.createOrder(loginUser.getId(), itemId, amount, promoId);
        return ResponseReturnType.create(null);
    }
}
